package cn.jw.starter.web;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import cn.jw.starter.web.common.ServiceStartResultHandler;
import cn.jw.starter.web.core.filters.CacheRequestBodyFilter;
import cn.jw.starter.web.core.properties.JwWebProperties;
import jakarta.servlet.Filter;

/**
 * web模块相关的自动化配置类
 *
 * @author 王广帅
 * @since 2024/4/2 0:53
 * @version 1.0
 */
@AutoConfiguration
@ServletComponentScan(basePackages = "cn.jw.starter.web.core.filters")
@EnableConfigurationProperties(JwWebProperties.class)
@ComponentScan(basePackages = "cn.jw.starter.web.common")
public class JwWebAutoConfiguration {

    // @Override
    // public void addInterceptors(InterceptorRegistry registry) {
    // registry.addInterceptor(new RequestLogInterceptor()).addPathPatterns("/**");
    // }

    @Bean
    public ServiceStartResultHandler serviceStartResultHandler() {
        return new ServiceStartResultHandler();
    }

    /**
     * 创建可重复读取的body的过虑器
     * 
     * @return 过虑器实例
     */
    @Bean
    public FilterRegistrationBean<CacheRequestBodyFilter> cacheRequestBodyFilter(JwWebProperties properties) {
        return createFilterBean(new CacheRequestBodyFilter(), properties.getWebFilterOrder().getCacheBodyFilterOrder());
    }

    /**
     * 创建 CorsFilter Bean，解决跨域问题
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterBean(JwWebProperties properties) {
        // 创建 CorsConfiguration 对象
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*"); // 设置访问源地址
        config.addAllowedHeader("*"); // 设置访问源请求头
        config.addAllowedMethod("*"); // 设置访问源请求方法
        // 创建 UrlBasedCorsConfigurationSource 对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对接口配置跨域设置
        return createFilterBean(new CorsFilter(source), properties.getWebFilterOrder().getCorsFilterOrder());
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(order);
        return bean;
    }
}
